package com.itheima.bos.web.action.system;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.itheima.bos.domain.system.User;
import com.itheima.bos.service.system.UserService;
import com.itheima.bos.web.common.action.BaseAction;
import com.opensymphony.xwork2.ActionContext;

@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
@Controller
public class UserAction extends BaseAction<User>{
	
	@Action(value="user_login",results={@Result(name="error",type="redirect",location="login.html"),
			@Result(name="success",location="index.html",type="redirect")})
	public String login(){
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken token = new UsernamePasswordToken(
				model.getUsername(),model.getPassword());
		System.out.println(model.getUsername()+"........"+model.getPassword());
		try {
			subject.login(token);
			return SUCCESS;
		} catch (AuthenticationException e) {
			e.printStackTrace();
			return ERROR;
		}	
	}
	
	@Action(value="user_logout",results={@Result(name="success",location="login.html",type="redirect")})
	public String logout(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return SUCCESS;	
	}
	
	@Autowired
	private UserService userService;
	
	@Action(value="user_list",results={@Result(name="success",type="json")})
	public String userQuery(){
		
		List<User> users = userService.findAll();
		ActionContext.getContext().getValueStack().push(users);
		return SUCCESS;	
	}
	
	private String[] roleIds;
	
	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}

	@Action(value="user_save",results={@Result(name="success",location="./pages/system/userlist.html",type="redirect")})
	public String save(){
		userService.saveUser(model,roleIds);
		return SUCCESS;	
	}
}
